package pers.zff.web.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

	private static final Log LOG = LogFactory.getLog(FileUtil.class);

	public static List<String> filesUpload(MultipartFile[] files, HttpServletRequest request) {
		List<String> list = new ArrayList<String>();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				list = saveFile(request, file, list);
			}
		}
		return list;
	}

	private static List<String> saveFile(HttpServletRequest request, MultipartFile file, List<String> list) {
		if (!file.isEmpty()) {
			try {
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
						+ file.getOriginalFilename();
				LOG.info(filePath);
				// list.add(file.getOriginalFilename());
				list.add(filePath);
				File saveDir = new File(filePath);
				if (!saveDir.getParentFile().exists())
					saveDir.getParentFile().mkdirs();
				file.transferTo(saveDir);
				return list;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}
}
